<template>
  <div class="mySelf-box">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'/admin/index',name:'AdminIndex'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人资料</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row :gutter="20" style="margin-top: 50px">
      <el-col :span="12">
        <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px" label-position="right">
          <el-form-item label="用户名">
            <el-input v-model="userForm.username" readonly></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="userForm.nickname" placeholder="请输入昵称（昵称将会代替用户名显示）..."></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <template>
              <div class="sex-box">
                <el-radio v-model="userForm.sex" label="男"></el-radio>
                <el-radio v-model="userForm.sex" label="女"></el-radio>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="个人简介" prop="introduce">
            <el-input type="textarea" v-model="userForm.introduce" :rows="5"
                      placeholder="请简要的介绍一下自己，内容不超过250个字..."></el-input>
          </el-form-item>
          <el-form-item label="QQ" prop="qq">
            <el-input placeholder="请输入您的qq号码..." v-model="userForm.qq"></el-input>
          </el-form-item>
          <el-form-item label="微信" prop="wechat">
            <el-input placeholder="请输入您的微信..." v-model="userForm.wechat"></el-input>
          </el-form-item>
          <el-form-item label="生日">
            <el-date-picker
              @change="dateChange"
              v-model="userForm.birthday"
              align="right"
              type="date"
              placeholder="选择出生日期..."
              style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="星座">
            <el-input placeholder="星座我会帮您算哦..." readonly v-model="userForm.constellations"></el-input>
          </el-form-item>
          <el-form-item label="生肖">
            <el-input placeholder="生肖我也会帮您算哦..." readonly v-model="userForm.animal"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="drawer = true"><i class="iconfont icon-mima btn-icon"></i>修改密码</el-button>
            <el-button type="primary" @click="resetForm('userForm')"><i class="iconfont icon-reset btn-icon"></i>重置
            </el-button>
            <el-button type="success" @click="save('userForm')"><i class="iconfont icon-ok btn-icon"></i>保存</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="10">
        <el-col :span="12" :offset="8">
          <el-upload
            class="upload-demo"
            :show-file-list="false"
            :action="this.$api.IMG_UPLOAD_URL"
            :on-success="onSuccess"
            :accept="accept"
            :headers="header"
            :on-error="onError">
            <div class="avatar-parent">
              <div class="avatar-shade"></div>
              <div class="avatar-shade-text">
                <div>
                  <i class="iconfont icon-upload"></i>
                  <span>上传头像</span>
                </div>
              </div>
              <div class="avatar-body">
                <el-avatar :size="300" :src="userForm.avatar"></el-avatar>
              </div>
            </div>
            <div class="el-upload__tip" slot="tip">只能上传{{ accept }}文件，且不超过2MB</div>
          </el-upload>
        </el-col>
      </el-col>
    </el-row>
    <el-drawer
      title="修改密码"
      :visible.sync="drawer"
      :direction="direction">
      <div class="pass-box">
        <el-form :model="passForm" :rules="passRules" label-position="right" label-width="80px" ref="passForm">
          <el-form-item prop="oldpassword" label="原始密码">
            <el-input type="password" prefix-icon="iconfont icon-mima1" show-password placeholder="请输入原始密码..."
                      v-model.trim="passForm.oldpassword"></el-input>
          </el-form-item>
          <el-form-item prop="password" label="新密码">
            <el-input type="password" prefix-icon="iconfont icon-mima1" show-password placeholder="请输入新密码..."
                      v-model.trim="passForm.password"></el-input>
          </el-form-item>
          <el-form-item prop="repassword" label="确认密码">
            <el-input type="password" prefix-icon="iconfont icon-mima1" show-password placeholder="确认密码..."
                      v-model.trim="passForm.repassword"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="resetForm('passForm')"><i class="iconfont icon-reset btn-icon"></i>重置
            </el-button>
            <el-button type="success" @click="updatePass('passForm')"><i class="iconfont icon-ok btn-icon"></i>提交
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  name: "MySelf",
  data() {
    let checkRepass = (rule, value, callback) => {
      if (value.trim() != this.passForm.password) {
        callback(new Error("两次密码不一致"));
      } else {
        callback();
      }
    }

    return {
      passForm: {
        id: this.$store.getters.getUserInfo.id,
        oldpassword: "",
        password: "",
        repassword: ""
      },
      direction: "ltr",
      drawer: false,
      uploadUrl: [],
      userForm: {
        id: "",
        username: "sunjun",
        nickname: "",
        sex: "男",
        introduce: "",
        qq: "",
        wechat: "",
        birthday: null,
        constellations: "",
        animal: "",
        avatar: "",
      },
      rules: {
        nickname: [
          {required: false, max: 10, message: "最多输入10个字符", trigger: "blur"}
        ],
        introduce: [
          {required: false, max: 250, message: "最多输入250个字符", trigger: "blur"}
        ],
        qq: [
          {required: false, pattern: /^[1-9][0-9]{4,14}$/, message: "请输入正确的qq号码", trigger: "blur"}
        ],
        wechat: [
          {required: false, max: 50, message: "最多输入50个字符", trigger: "blur"}
        ],

      },
      accept: '.jpg,.jpeg,.png,.gif,.tiff',
      header: {
        Authorization: this.$store.getters.getToken
      },
      passRules: {
        oldpassword: [
          {required: true, message: "请输入原始密码", trigger: "blur"},
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W\.]{6,18}$/,
            message: "密码必须包含数字和字母，可以有特殊字符长度为6-18个字符",
            trigger: 'blur'
          }
        ],
        password: [
          {required: true, message: "请输入新密码", trigger: 'blur'},
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W\.]{6,18}$/,
            message: "密码必须包含数字和字母，可以有特殊字符长度为6-18个字符",
            trigger: 'blur'
          }
        ],
        repassword: [
          {required: true, message: "请再次输入密码", trigger: 'blur'},
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W\.]{6,18}$/,
            message: "密码必须包含数字和字母，可以有特殊字符长度为6-18个字符",
            trigger: 'blur'
          },
          {validator: checkRepass, trigger: "blur"}
        ],
      }
    }
  },
  created() {
    this.userForm = this.Storage.Local.get("userInfo");
    console.log(this.userForm)
  },
  methods: {
    updatePass(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$post(this.$api.USER_UPDATE_PASS_URL, this.passForm).then(res => {
            if (res.data.code == 200) {
              this.$notify({
                title: "成功",
                message: res.data.message,
                type: "success"
              });
              this.$get(this.$api.LOGOUT_URL, {}).then(logoutRes => {
                console.log(logoutRes);
                if (logoutRes.data.code == 200) {
                  this.$store.commit("setToken", null);
                  this.$store.commit("setUserInfo", null);
                  if (this.$route.path.indexOf('admin') > -1) {
                    this.$router.push({
                      path: '',
                      name: 'Index'
                    });
                  }
                }
              })
            }
          })
        }
      })
    },
    dateChange() {
      if (this.userForm.birthday) {
        this.$get(this.$api.GENERATE_BIRTH_INFO_URL + "/" + this.userForm.birthday.format("yyyy-MM-dd"), {}).then(res => {
          if (res.data.code == 200) {
            this.userForm.constellations = res.data.data.constellations;
            this.userForm.animal = res.data.data.animal;
          }
        })
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.userForm.createTime = null;
          this.userForm.updateTime = null;
          this.$post(this.$api.USER_UPDATE_URL, this.userForm).then(res => {
            console.log(res);
            if (res.data.code == 200) {
              this.$notify.success(res.data.message);
              this.$get(this.$api.USER_DETAIL_URL + `/${this.userForm.id}`, {}).then(resUser => {
                console.log(resUser);
                if (resUser.data.code == 200) {
                  this.$store.commit('setUserInfo', resUser.data.data.userInfo);
                } else {
                  this.$notify.error("获取用户信息出现问题");
                  this.$get(this.$api.LOGOUT_URL, {}).then(logoutRes => {
                    console.log(logoutRes);
                    if (logoutRes.data.code == 200) {
                      this.$store.commit("setToken", null);
                      this.$store.commit("setUserInfo", null);
                      if (this.$route.path.indexOf('admin') > -1) {
                        this.$router.push({
                          path: '',
                          name: 'Index'
                        });
                      }
                    }
                  })
                }
              });
              this.uploadUrl.pop();
              if (this.uploadUrl.length != 0) {
                this.$del(this.$api.IMG_DELETE_BATCHES_URL, {
                  fileNames: this.uploadUrl.join(',')
                }).then(delRes => {
                  console.log('delRes', delRes)
                })
              }
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.$notify.success("上传成功");
        this.userForm.avatar = response.data.url;
        this.uploadUrl.push(response.data.url);
      }
    },
    onError(err, file, fileList) {
      this.$notify.error(JSON.parse(err.message).message);
    },
  }
}
</script>

<style scoped>
.btn-icon {
  font-size: 16px;
  margin-right: 5px;
}

.avatar-parent {
  position: relative;
  width: 100%;
  height: 300px;
  border-radius: 50%;
  overflow: hidden;
}

.avatar-parent .avatar-shade {
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: .3;
  border-radius: 50%;
  background: #2d2d2d;
  z-index: 2;
  display: none;
  text-align: center;
}

.avatar-parent .avatar-shade-text {
  position: absolute;
  width: 100%;
  height: 100%;
  display: none;
  color: #ffffff;
  font-weight: bolder;
  z-index: 3 !important;
}

.avatar-parent .avatar-shade-text > div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.avatar-parent:hover .avatar-shade, .avatar-parent:hover .avatar-shade-text {
  display: block;
}

.pass-box {
  padding: 10px 50px;
}
</style>
